package com.github.thinwonton.springboot.showcase.transaction.propagation.service.propagation_requires_new;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class PaymentService {
	@Autowired
	private AccountService accountService;

	@Autowired
	private OrdersService ordersService;

	//	@Transactional(rollbackFor = Exception.class)
	public void pay(Long accountId, Long orderId, BigDecimal money) {
		accountService.changeMoney(accountId, money);
		ordersService.updateStatus(orderId);
	}

	//	@Transactional(rollbackFor = Exception.class)
	public void pay2(Long accountId, Long orderId, BigDecimal money) {
		accountService.changeMoney(accountId, money);
		ordersService.updateStatusThrowException(orderId);
	}

	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void pay3(Long accountId, Long orderId, BigDecimal money) {
		accountService.changeMoney(accountId, money);
		ordersService.updateStatusThrowException(orderId);
	}

	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
	public void pay4(Long accountId, Long orderId, BigDecimal money) {
		accountService.changeMoneyNoTx(accountId, money);
		ordersService.updateStatusNoTxThrowException(orderId);
	}

	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
	public void pay5(Long accountId, Long orderId, BigDecimal money) {
		accountService.changeMoneyNoTx(accountId, money);
		try {
			ordersService.updateStatusNoTxThrowException(orderId);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void pay6(Long accountId, Long orderId, BigDecimal money) {
		accountService.changeMoney(accountId, money);
		try {
			ordersService.updateStatusThrowException(orderId);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void pay7(Long accountId, Long orderId, BigDecimal money) {
		accountService.changeMoney(accountId, money);
		try {
			ordersService.updateStatusThrowException(orderId);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
